<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" href="style.css">
		<script src="jquery.min.js"></script>
	</head>
	<body>
		<div class="box">
			<div class="test">
				<div class="testbox">
					<h2>ToDoList</h2>
					<input type="text" id="testinput">
					<button id="btnadd">添加</button>
				</div>
			</div>
			<div class="wrap">
				<div class="head">
					<h2>正在进行</h2><span class="count1">0</span>
				</div>
				<ul class="underway">
				</ul>
				<li id="template"><input class="add" type="checkbox"><span class="itmecont"></span><button class="delete">-</button></li>
				<div class="head">
					<h2>已经完成</h2><span class="count2">0</span>
				</div>
				<ul class="completed">
				</ul>
			</div>
		</div>
	</body>
</html>
<script>
	let template = $("#template");
	let underway = $(".underway");
	let completed = $(".completed");
	let testinput = $("#testinput");
	$(function(){
		let list = JSON.parse(localStorage.getItem("data"));
		if(list!==null){
			list.forEach(function(item){
				let newItem = template.clone(true);
				newItem.attr("id", "").prependTo(underway).find(".itmecont").html(item.text);
				if(item.isdoing){
					newItem.appendTo(completed);
					newItem.find("input")[0].checked=true;
				}else{
					newItem.appendTo(underway)
				}
			}) 
		}
	})
	function count() {
		$(".count1").html($(".underway li").length);
		$(".count2").html($(".completed li").length);
	}
	$("#btnadd").click(function() {
		if (testinput.val() !== "") {
			let newItem = template.clone(true);
			newItem.attr("id", "").prependTo(underway).find(".itmecont").html(testinput.val());
			testinput.val("");
		}
		count();
		getJSON()
	})
	testinput.keydown(function(event) {
		if (event.keyCode === 13) {
			$("#btnadd").click();
		}
	})
	$(".delete").click(function() {
		$(this).closest("li").fadeOut(function() {
			$(this).remove();
			count();
			getJSON()
		})
	})
	$(".add").click(function() {
		if ($(this).prop("checked")) {
			$(this).closest("li").appendTo(completed);
		} else {
			$(this).closest("li").appendTo(underway);
		}
		count();
		getJSON()
	})
	$(".itmecont").click(function() {
		let html = $(this).html();
		if ($(this).find("input").length === 0) {
			$(this).html(`<input class="testboxs" type="text" value=${html}>`).find("input").select();
		}
		$(this).find("input").blur(function() {
			let nowhtml = $(this).val()
			$(this).closest(".itmecont").html(nowhtml);
			getJSON()
		})
	})
	function getJSON(){
		let underwayList = $(".underway li");
		let completedList = $(".completed li");
		let result=[];
		underwayList.each(function(){
			let item = {}
			item.text = $(this).find(".itmecont").html();
			item.isdoing = false;
			result.push(item)
		})
		completedList.each(function(){
			let item = {}
			item.text = $(this).find(".itmecont").html();
			item.isdoing = true;
			result.push(item)
		})
		localStorage.setItem("data",JSON.stringify(result))
	}
</script>
